﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Windows.Forms;

namespace Twofolders
{
    public partial class TwofoldersForm : Form
    {
        private List<FolderPair> m_folderPairs = new List<FolderPair>();

        public TwofoldersForm()
        {
            InitializeComponent();
        }

        private void TwofoldersForm_Load(object sender, EventArgs e)
        {
            m_versionTextBox.Text = "0.5.0";
            ReadFolderPairs();
            PopulateFolderPairs();
            DetermineButtonsEnabledState();

            m_toolTip.SetToolTip(m_upButton, "Moving a folder pair up increases its priority, ensuring it is run before all folder pairs after it.");
            m_toolTip.SetToolTip(m_downButton, "Moving a folder pair up decreases its priority, making it run after all folder pairs before it.");
        }

        private void ListView_ItemChecked(object sender, System.Windows.Forms.ItemCheckedEventArgs e)
        {
            DetermineButtonsEnabledState();
        }

        private void ListView_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            //TODO[karthik]: do ascending/descending toggle sorting
        }

        private void NewButton_Click(object sender, EventArgs e)
        {
            NewFolderPairForm form = new NewFolderPairForm(m_folderPairs);
            if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                m_folderPairs.Add(form.NewFolderPair);
                AddFolderPairToListView(form.NewFolderPair);
                PersistFolderPairs();
            }
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            List<string> folderPairsToDelete = new List<string>();
            foreach (ListViewItem checkedItem in m_listView.CheckedItems)
            {
                folderPairsToDelete.Add(checkedItem.SubItems[0].Text);
            }

            foreach (var toDelete in folderPairsToDelete)
            {
                m_folderPairs.Remove(FolderPair.GetByName(m_folderPairs, toDelete));
                m_listView.Items.RemoveByKey(toDelete);
            }
            
            PersistFolderPairs();
            DetermineButtonsEnabledState();
        }

        private void BackupButton_Click(object sender, EventArgs e)
        {
            m_notifyIcon.Icon = Properties.Resources.TwofoldersRunningIcon;
            Dictionary<FolderPair, ListViewItem> folderPairItems = new Dictionary<FolderPair, ListViewItem>();
            foreach (ListViewItem item in m_listView.Items)
            {
                if (item.Checked)
                {
                    folderPairItems.Add(FolderPair.GetByName(
                        m_folderPairs, item.SubItems[0].Text), item);
                }
            }
            BackupRunner.RunBackup(folderPairItems, m_notifyIcon);            
        }
        
        private void StopButton_Click(object sender, EventArgs e)
        {
            StopAllBackups();
        }

        private void UpButton_Click(object sender, EventArgs e)
        {
            StopAllBackups();

            for (int i = 1; i < m_listView.Items.Count; i++)
            {
                if (m_listView.Items[i].Checked)
                {
                    FolderPair toMoveUp = m_folderPairs[i];
                    FolderPair toMoveDown = m_folderPairs[i - 1];

                    m_folderPairs[i] = toMoveDown;
                    m_folderPairs[i - 1] = toMoveUp;
                    
                    PersistFolderPairs();
                    PopulateFolderPairs();
                    m_listView.Items[i - 1].Checked = true;

                    break;
                }
            }            
        }

        private void DownButton_Click(object sender, EventArgs e)
        {
            StopAllBackups();

            for (int i = 0; i < m_listView.Items.Count - 1; i++)
            {
                if (m_listView.Items[i].Checked)
                {
                    FolderPair toMoveDown = m_folderPairs[i];
                    FolderPair toMoveUp = m_folderPairs[i + 1];

                    m_folderPairs[i] = toMoveUp;
                    m_folderPairs[i + 1] = toMoveDown;

                    PersistFolderPairs();
                    PopulateFolderPairs();
                    m_listView.Items[i + 1].Checked = true;

                    break;
                }
            }
        }

        private void AllNoneCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in m_listView.Items)
            {
                item.Checked = m_allNoneCheckBox.Checked;
            }
        }

        private void TwofoldersWebsiteLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            m_2foldersWebsiteLinkLabel.LinkVisited = true;
            System.Diagnostics.Process.Start(m_2foldersWebsiteLinkLabel.Text);
        }

        private void ReadFolderPairs()
        {
            if (Properties.Settings.Default.FolderPairs == null) return;

            foreach (string folderPair in Properties.Settings.Default.FolderPairs)
            {
                string[] split = folderPair.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                bool toDelete = false;
                bool.TryParse(split[3], out toDelete);
                m_folderPairs.Add(new FolderPair(split[0], split[1], split[2], toDelete));
            }
        }

        private void PopulateFolderPairs()
        {
            m_listView.Items.Clear();
            foreach (var folderPair in m_folderPairs)
            {
                AddFolderPairToListView(folderPair);
            }
        }

        private void AddFolderPairToListView(FolderPair folderPair)
        {
            ListViewItem item = new ListViewItem(folderPair.Name);
            item.Name = folderPair.Name;
            item.SubItems.Add(folderPair.SourceDirectory);
            item.SubItems.Add(folderPair.DestinationDirectory);
            item.SubItems.Add("");
            item.SubItems.Add(
                folderPair.ShouldDeleteFromDestination.ToString().ToLower() == "true" ? "Yes" : "No");
            m_listView.Items.Add(item);
        }

        private void PersistFolderPairs()
        {
            Properties.Settings.Default.FolderPairs = new StringCollection();
            foreach (var folderPair in m_folderPairs)
            {
                Properties.Settings.Default.FolderPairs.Add(
                    string.Format("{0}|{1}|{2}|{3}", 
                    folderPair.Name, folderPair.SourceDirectory, folderPair.DestinationDirectory, 
                    folderPair.ShouldDeleteFromDestination.ToString()));
            }
            Properties.Settings.Default.Save();
        }

        private void DetermineButtonsEnabledState()
        {
            m_backupButton.Enabled = m_stopButton.Enabled = m_deleteButton.Enabled = m_listView.CheckedItems.Count > 0;
            m_upButton.Enabled = m_downButton.Enabled = (m_listView.CheckedItems.Count == 1);            
        }

        private void StopAllBackups()
        {
            foreach (ListViewItem checkedItem in m_listView.CheckedItems)
            {
                BackupRunner.StopBackup(FolderPair.GetByName(m_folderPairs, checkedItem.SubItems[0].Text));
            }
        }
    }
}
